<template>
  <div class="app-container layout-container audit-container-box">
    <Breadcrumb />
    <div class="app-container layout-container audit-container">
      <a-form :model="params" auto-label-width>
        <div class="flex-space">
          <a-form-item label="审批类型">
            <SelectSearch
              :defaultSelectId="params.formId"
              :requestApi="modelGroupList"
              :config="searchFormConfig"
              @change-select="changeAuditType"
            />
          </a-form-item>
          <a-form-item label="发起人">
            <a-input placeholder="请输入" v-model="params.keyword" />
          </a-form-item>
          <a-form-item label="审批提交日期">
            <a-range-picker @change="changeRangePicker as any" />
          </a-form-item>
          <a-button type="primary" @click="handeSearch">
            <template #icon>
              <icon-search />
            </template>
            查询
          </a-button>
        </div>
      </a-form>
      <a-tabs @change="changeAuditStatus as any">
        <a-tab-pane v-for="item in config.auditTypes" :key="item.value" :title="item.label"></a-tab-pane>
      </a-tabs>
      <a-table :columns="tableColumn" :data="auditList" :pagination="false" :scroll="{ y: '100%' }">
        <template #taskName="{ record }">
          <span>{{ auditListType === "my" ? record.instanceName : record.taskName }}</span>
        </template>
        <template #status="{ record }">
          <a-tag v-if="auditListType === 'pending'" color="orange">待审批</a-tag>
          <a-tag v-else-if="auditListType === 'approved'" :color="auditStatusLabel(record)[0]">
            {{ auditStatusLabel(record)[1] }}
          </a-tag>
          <a-tag v-else :color="auditStatusLabel(record) as any">{{ record.status }}</a-tag>
        </template>
        <template #operate="{ record }">
          <a-button v-if="auditListType === 'pending'" type="text" size="mini" @click="handelApproval(record)">审批 </a-button>
          <a-button v-else type="text" size="mini" @click="handelCheckApproval(record)">查看</a-button>
        </template>
      </a-table>

      <a-pagination
        :total="total"
        v-model:current="params.pageNo"
        v-model:page-size="params.pageSize"
        @change="handleChangePagination"
        @page-size-change="handleChangeSizePagination"
        show-total
        show-jumper
        show-page-size
      />
    </div>

    <!--    审批  -->
    <a-drawer
      :visible="auditVisible"
      :footer="false"
      :width="900"
      title-align="start"
      :header="false"
      @cancel="handleDrawerCancel"
      unmountOnClose
    >
      <div class="handel-container">
        <div class="drawer-title">
          <div style="display: flex">
            <custom-title :title="drawerTitle" />
          </div>
          <IconClose style="cursor: pointer" @click="handleDrawerCancel" />
        </div>
        <div class="handel-container-body">
          <div
            class="form-container"
            :style="{
              height: isAcceptanceTask ? 'calc(100vh - 113px)' : 'calc(100vh - 60px)',
              'padding-top': isAcceptanceTask ? '0px' : '20px'
            }"
          >
            <a-button type="text" style="margin: 10px 0; padding-left: 0" @click="handelCheckStandard" v-show="isAcceptanceTask"
              >查看标准</a-button
            >
            <div class="form-items" v-if="auditVisible">
              <div>审批ID：{{ auditInstanceId }}</div>
              <micro-app
                class="micro-app"
                name="form-design-audit"
                :url="appUrlconfig.formDesign"
                default-page="/audit"
                baseroute="/form-design"
                :data="{ token: getToken() }"
                router-mode="native"
              />
            </div>
          </div>
          <div class="followUp-container">
            <div class="title">审批记录</div>
            <div class="audit-list">
              <template v-if="auditRecordList.length">
                <div class="audit-item" v-for="item in auditRecordList">
                  <div class="audit-header">
                    <img :src="Avatar" alt="" />
                    <div>
                      <div class="audit-title">
                        {{ item.name }} <span>{{ item.finishTime }}</span>
                      </div>
                      <div class="audit-status">{{ auditUser(item) }}({{ auditResult(item) }})</div>
                    </div>
                  </div>
                  <div :class="{ 'audit-desc': true, divider: true }">
                    <div class="content" v-show="item.comment?.length">
                      <a-textarea :default-value="comment(item)" auto-size disabled />
                    </div>
                  </div>
                </div>
              </template>
              <a-empty v-else />
            </div>
            <div class="audit-btn-container">
              <a-textarea v-if="!isAuditDisabled" placeholder="请输入审批意见" v-model.trim="commentData" />
              <div class="form-btns" v-if="!isAuditDisabled">
                <a-button style="width: 92px; background-color: #f2f3f5" type="secondary" @click="handelAuditRefuse"
                  >拒绝</a-button
                >
                <a-button style="width: 92px" type="primary" @click="handelAuditAgree">同意</a-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-drawer>

    <!--    验收标准  -->
    <a-modal v-model:visible="isShowStandard" unmount-on-close :width="900" title-align="start">
      <template #title>
        <CustomTitle title="查看" />
      </template>
      <template #footer><div></div></template>
      <a-form :model="standardForm" auto-label-width>
        <template v-for="(item, index) in standardForm.fieldData" :key="`${item.fieldName}${index}`">
          <a-form-item :label="item.fieldName" v-if="!item.valueComplex">
            <a-textarea :auto-size="{ minRows: 3 }" v-model="item.fieldValue" readonly />
          </a-form-item>
          <a-form-item :label="item.fieldName" v-if="item.valueComplex && item.fieldValue.length">
            <a-image-preview-group infinite v-if="item.fileContextType === 'image'">
              <a-space wrap>
                <a-image
                  v-for="imgItem in item.fieldValue"
                  :key="imgItem.fileId"
                  :src="imgItem.fileUrl"
                  width="80"
                  height="80"
                  fit="cover"
                />
              </a-space>
            </a-image-preview-group>
            <a-space wrap v-if="item.fileContextType === 'video'">
              <video
                v-for="videoItem in item.fieldValue"
                :key="videoItem.fileId"
                @click="handlePreview(videoItem.fileUrl)"
                :src="videoItem.fileUrl"
                style="width: 80px; height: 80px; object-fit: cover"
              ></video>
            </a-space>
          </a-form-item>
        </template>
      </a-form>
    </a-modal>

    <!--   预览视频 -->
    <a-modal v-model:visible="isShowPreview" unmount-on-close title-align="start" :width="900">
      <template #title>
        <CustomTitle title="视频预览" />
      </template>
      <template #footer><div></div></template>
      <video
        v-if="isShowPreview"
        :src="previewVideoUrl"
        controls
        style="width: 100%; height: 50vh; object-fit: cover; cursor: pointer"
      ></video>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { Message } from "@arco-design/web-vue";
import _ from "lodash";
import Avatar from "@/assets/images/default-avatar.png";
import { pendingAuditList, alreadyAuditList, myAuditList, approvalForm, handlerTask, modelGroupList } from "@/apis/audit";
import { standardInfoByBusinessKey } from "@/apis";
import type { modelItem, AuditStatus, StandardForm, AuditRecordItem } from "./types";
import type { AuditListParams } from "@/apis/audit/types";
import * as config from "./config";

import Breadcrumb from "@/components/Breadcrumb/index.vue";
import appUrlconfig from "@/config/appUrlconfig";
import { getToken } from "@/utils/auth";
import { mainRemoveDataListener, mainSendForceSetData, unmountApp } from "@/microApp/utils";
import { useUserStore } from "@/stores";

const userStore = useUserStore();

const searchFormConfig = {
  label: "formName",
  value: "formId",
  keyword: "modelName"
};

const params = ref({
  pageNo: 1,
  pageSize: 10,
  startTimes: "",
  keyword: "",
  formId: ""
});
const total = ref(0);
const tableColumn = ref([...config.columns]);
const auditList = ref([]);
const myAuditStatus = new Map([
  ["RUNNING", "orange"],
  ["PASS", "blue"],
  ["REFUSE", "red"]
]);
const approvedAuditStatus = new Map([
  ["refuse", ["red", "已拒绝"]],
  ["recall", ["red", "已拒绝"]], // 退回
  ["agree", ["blue", "已同意"]]
]);
// ToDo：暂时使用该方式
const auditStatusLabel = computed(() => {
  return (data: any) => {
    if (auditListType.value === "my") {
      return myAuditStatus.get(data.result) || "";
    } else if (auditListType.value === "approved") {
      return approvedAuditStatus.get(data.taskResult) || ["red", "数据错误"];
    } else {
      return "";
    }
  };
});
const getPendingAuditList = async (paramsData: AuditListParams) => {
  const { data } = await pendingAuditList(paramsData);
  auditList.value = data?.records || [];
  auditList.value.forEach((item: any) => {
    item.ownerName = item.owner?.name;
  });
  total.value = data?.total || 0;
};
const getAlreadyAuditList = async (paramsData: AuditListParams) => {
  const { data } = await alreadyAuditList(paramsData);
  auditList.value = data?.records || [];
  auditList.value.forEach((item: any) => {
    item.ownerName = item.owner?.name;
  });
  total.value = data?.total || 0;
};
const getMyAuditList = async (paramsData: AuditListParams) => {
  const { data } = await myAuditList(paramsData);
  auditList.value = data?.records || [];
  auditList.value.forEach((item: any) => {
    item.ownerName = userStore.userInfo?.nickName || "";
    item.createTime = item.startTime;
  });
  total.value = data?.total || 0;
};

/**
 *TODO: 目前仅加载审批表单
 */
const auditListType = ref("pending");
const getAuditListData = () => {
  const paramsData = {
    ...params.value,
    code: params.value.formId === "-1" ? "" : params.value.formId
  };
  switch (auditListType.value) {
    case "pending":
      getPendingAuditList(paramsData);
      break;
    case "approved":
      getAlreadyAuditList(paramsData);
      break;
    case "my":
      getMyAuditList(paramsData);
      break;
  }
};
const handleChangePagination = async (val: number) => {
  params.value.pageNo = val === 0 ? 1 : val;
  getAuditListData();
};
const handleChangeSizePagination = (val: number) => {
  params.value.pageSize = val;
  getAuditListData();
};
const changeAuditType = (typeObj: any) => {
  params.value.formId = typeObj.formId;
  params.value.pageNo = 1;
  getAuditListData();
};
const changeRangePicker = (data: string[]) => {
  params.value.pageNo = 1;
  params.value.startTimes = data?.join(",") || "";
  getAuditListData();
};
const changeAuditStatus = (data: AuditStatus) => {
  auditListType.value = data;
  params.value.pageNo = 1;
  auditList.value = [];
  getAuditListData();
};
const handeSearch = _.debounce(getAuditListData, 500);

/**
 * 审批
 */
const auditVisible = ref(false);
const drawerTitle = ref("");
const auditInstanceId = ref("");
const isAuditDisabled = ref(false);
const auditRecordList = ref<AuditRecordItem[]>([]);
const auditStatusMap = new Map([
  ["complete", "发起申请"],
  ["refuse", "已拒绝"],
  ["recall", "已拒绝"], // 退回
  ["agree", "已同意"],
  ["info", "已取消"]
]);
// TODO:计算属性传参问题
const auditResult = computed(() => {
  return (data: any) => {
    if (!data?.result) {
      return "审批中";
    }
    return auditStatusMap.get(data.result) || "";
  };
});
const auditUser = computed(() => {
  return (data: any) => {
    return data.user?.name || "";
  };
});
const comment = computed(() => {
  return (data: any) => {
    return data?.comment?.length ? data?.comment[0]?.text : "";
  };
});
const handelApproval = (auditData: any) => {
  auditVisible.value = true;
  isAuditDisabled.value = false;
  drawerTitle.value = auditData.taskName;
  auditPostData.value.instanceId = auditData.instanceId;
  auditPostData.value.taskId = auditData.taskId;
  auditPostData.value.nodeId = auditData.nodeId;
  getApprovalFormData(auditData.instanceId, auditData.nodeId);
  mainSendForceSetData("form-design-audit", {
    auditData,
    isAuditCenterDisabled: true
  });
};
const handelCheckApproval = (auditData: any) => {
  auditVisible.value = true;
  isAuditDisabled.value = true;
  drawerTitle.value = auditData.processDefName;
  auditPostData.value.instanceId = auditData.instanceId;
  auditPostData.value.taskId = auditData.taskId;
  auditPostData.value.nodeId = auditData.nodeId;
  getApprovalFormData(auditData.instanceId, auditData.nodeId);
  mainSendForceSetData("form-design-audit", {
    auditData,
    isAuditCenterDisabled: true
  });
};
const getApprovalFormData = async (instanceId: string, nodeId: string) => {
  try {
    const { data } = await approvalForm(instanceId, nodeId);
    auditInstanceId.value = data?.instanceId ?? "";
    businessKey.value = data?.businessKey || "";
    isAcceptanceTask.value = data.formId?.includes("acceptance") || "";
    auditRecordList.value = data?.progress || [];
    auditPostData.value.formData = data?.formData || {};
  } catch (err) {
    console.log("加载审批记录>>>>", err);
  }
};

/**
 * 验收审批-查看验收标准
 */
const isShowStandard = ref(false);
const isAcceptanceTask = ref(false);
const isShowPreview = ref(false);
const businessKey = ref("");
const standardForm = ref<StandardForm>({
  imageList: [],
  videoList: [],
  fieldData: []
});
const previewVideoUrl = ref("");
const handelCheckStandard = async () => {
  const { data } = await standardInfoByBusinessKey(businessKey.value);
  if (!data) return Message.error("数据错误");
  standardForm.value.fieldData = data || [];
  isShowStandard.value = true;
};
const handlePreview = (url: string) => {
  previewVideoUrl.value = url;
  isShowPreview.value = true;
};

/**
 * 提交审批
 */
const commentData = ref("");
const auditPostData = ref<any>({});
const handelAuditAgree = async () => {
  auditPostData.value.action = "agree";
  commentData.value && (auditPostData.value.comment = { text: commentData.value });
  await handlerTask(auditPostData.value);
  handleDrawerCancel();
  Message.success("操作成功");
  getAuditListData();
};
const handelAuditRefuse = async () => {
  auditPostData.value.action = "refuse";
  commentData.value && (auditPostData.value.comment = { text: commentData.value });
  await handlerTask(auditPostData.value);
  handleDrawerCancel();
  Message.success("操作成功");
  getAuditListData();
};
const handleDrawerCancel = () => {
  auditVisible.value = false;
  commentData.value = "";
  auditPostData.value = {};
  auditRecordList.value = [];
  unmountApp("form-design-audit");
};

getAuditListData();
</script>

<style scoped lang="scss">
@import "index";
</style>
